//
// Created by maqz on 2018/4/2.
// Copyright (c) 2018 毛毛驴. All rights reserved.
//

#import "LKBoTongFeedbackBaseWebViewController.h"
#import "FBAdapter.h"
#import "Masonry.h"

@interface LKBoTongFeedbackBaseWebViewController ()<WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler>
@property (strong, nonatomic)UIButton *errorReloadButton;
@property (copy, nonatomic)NSString *url;
@property (nonatomic, assign) UIDeviceOrientation deviceOrientation;

@end

static NSString *const webViewEstimatedProgressKey = @"estimatedProgress";
static NSString *const webViewCanGoBackKey = @"canGoBack";
static NSString *const webViewTitleKey = @"title";

@implementation LKBoTongFeedbackBaseWebViewController

// MARK: Lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.leftBarButtonItems = @[[self leftBackBarButtonItem], [self closeBarButtonItem]];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self initializeComponent];
    
    [self addWebViewObserver];
    
    // 点击 home 键返回桌面然后再进入 app 时，设备的 orientation 发生了改变
    // 通过记录返回桌面时的 orientation 然后在进入 APP 时重新赋值
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
}

- (void)dealloc {
    [_webView removeObserver:self forKeyPath:webViewEstimatedProgressKey];
    [_webView removeObserver:self forKeyPath:webViewCanGoBackKey];
    [_webView removeObserver:self forKeyPath:webViewTitleKey];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.view setNeedsLayout];
    [self.navigationController.view layoutIfNeeded];
}

#pragma mark - app notification

- (void)appDidEnterBackground {
    self.deviceOrientation = [UIDevice currentDevice].orientation;
}

- (void)appDidBecomeActive {
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:self.deviceOrientation] forKey:@"orientation"];
}

// MARK: Private method

- (void)initializeComponent {
    _scriptMessages = [NSMutableDictionary dictionary];
    
    WKWebViewConfiguration *webViewConfiguration = [[WKWebViewConfiguration alloc] init];
    _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:webViewConfiguration];
    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
    _webView.scrollView.bounces = NO;
    [self.view addSubview:_webView];
    
    _progressView = [[UIProgressView alloc] init];
    [_progressView setTrackTintColor:[UIColor clearColor]];
    [_progressView setTintColor:[UIColor redColor]];
    [self.view addSubview:_progressView];
    
    _errorReloadButton = [[UIButton alloc] init];
    [_errorReloadButton setTitle:@"点击重新加载" forState:UIControlStateNormal];
    [_errorReloadButton setTitleColor:[self hexColor:(0xD1D1D1)] forState:UIControlStateNormal];
    _errorReloadButton.titleLabel.font = kBTFont(16);
    [_errorReloadButton addTarget:self action:@selector(errorReloadButtonCkick:) forControlEvents:UIControlEventTouchUpInside];
    _errorReloadButton.hidden = YES;
    [self.view addSubview:_errorReloadButton];

    [self makeConstraints];
}

- (void)makeConstraints {
    
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11, *)) {
            make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
        }
        else {
            make.top.mas_equalTo(self.view).offset(0);
        }
        make.left.right.bottom.mas_equalTo(0);
    }];
    
    [_progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11, *)) {
            make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
        }
        else {
            make.top.mas_equalTo(self.view).offset(0);
        }
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(1.5);
    }];
    
    [_errorReloadButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.mas_equalTo(0);
        make.width.mas_equalTo(kBTFloat(300));
        make.height.mas_equalTo(kBTFloat(100));
    }];
}

- (void)addWebViewObserver {
    [_webView addObserver:self forKeyPath:webViewEstimatedProgressKey options:NSKeyValueObservingOptionNew context:nil];
    [_webView addObserver:self forKeyPath:webViewCanGoBackKey options:NSKeyValueObservingOptionNew context:nil];
    [_webView addObserver:self forKeyPath:webViewTitleKey options:NSKeyValueObservingOptionNew context:nil];
}

- (UIBarButtonItem *)leftBackBarButtonItem {
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"FB_back"] style:UIBarButtonItemStylePlain target:self action:@selector(leftBackBarButtonItemAction:)];
    // 解决 web 页和非web 页来回切换时，返回箭头的位置偏移问题
//    item.imageInsets = UIEdgeInsetsMake(1, -8, -1, 8);
    return item;
}

- (UIBarButtonItem *)closeBarButtonItem {
//    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[self closeImage] style:UIBarButtonItemStylePlain target:self action:@selector(closeBarButtonItemAction:)];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(closeBarButtonItemAction:)];
//    item.imageInsets = UIEdgeInsetsMake(0, -28, 0, 28);
    return item;
}


- (UIImage *)closeImage {
    return [UIImage imageNamed:@"LKBoTongFeedback_navigation_close"];
}

//MARK: Bar button item action
- (void)leftBackBarButtonItemAction:(UIBarButtonItem *)sender {
    if (_webView.canGoBack) {
        [_webView goBack];
    } else {
        [_webView stopLoading];
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

- (void)closeBarButtonItemAction:(UIBarButtonItem *)sender {
    // 停止所有网络请求
    [_webView stopLoading];
    
    // 关闭页面时如果是横屏状态则改为竖屏（横屏状态下按 home 键返回桌面再进入后，设备的 orientation 为 unknow，所以判断是否为横屏时总为 no）
    
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        BOOL isLandscap = NO;
        id delegate = [UIApplication sharedApplication].delegate;
        SEL selector = NSSelectorFromString(@"setAllowAutoRotate:");
        if ([delegate respondsToSelector:selector]) {
            NSMethodSignature *methodSignature = [delegate methodSignatureForSelector:selector];
            NSInvocation *invcation = [NSInvocation invocationWithMethodSignature:methodSignature];
            [invcation setTarget:delegate];
            [invcation setSelector:selector];
            [invcation setArgument:&isLandscap atIndex:2];
            [invcation invoke];
        }
        
        [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationPortrait] forKey:@"orientation"];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

//MARK: Button click
- (void)errorReloadButtonCkick:(UIButton *)sender {
    if (_webView.URL) {
        [_webView reload];
    }
    else [self loadWebViewWithURL:_url];
}

//MARK: Public method

- (void)loadWebViewWithURL:(NSString *)url {
    _url = url;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [_webView loadRequest:request];
}

- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(id _Nullable, NSError * _Nullable))completionHandler {
    [self.webView evaluateJavaScript:javaScriptString completionHandler:completionHandler];
}

- (void)addScriptMessageHandlerWithName:(NSString *)name {
    [_webView.configuration.userContentController addScriptMessageHandler:self name:name];
}

- (void)scriptMessage:(WKScriptMessage *)message {
    
}

- (void)updateSubViewsTopConstrint:(CGFloat)top {
    [self.progressView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).offset(top);
    }];
    
    [_webView mas_updateConstraints:^(MASConstraintMaker *make) {
       make.top.mas_equalTo(self.view).offset(top);
    }];
}

//MARK: Observer
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if (object != _webView) {
        return;
    }
    if ([keyPath isEqualToString:webViewEstimatedProgressKey]) {
        _progressView.hidden = _webView.estimatedProgress == 1;
        [_progressView setProgress:_webView.estimatedProgress animated:YES];
    }
    if ([keyPath isEqualToString:webViewCanGoBackKey]) {

    }
    if ([keyPath isEqualToString:webViewTitleKey]) {
        NSLog(@" tttt -- Load web view progress: %f", _webView.estimatedProgress);
        self.navigationItem.title = _webView.title;
    }
}

// MARK: WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    [_scriptMessages setObject:message.body forKey:message.name];
    [self scriptMessage:message];
}

// MARK: Web view navigation delegate
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    self.navigationItem.title = @"加载失败";
    if (_errorReloadButton.hidden == YES) {
        _errorReloadButton.hidden = NO;
    }
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"Alert" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alertVC addAction:confirmAction];
    [self presentViewController:alertVC animated:YES completion:nil];
    completionHandler();
    
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    _errorReloadButton.hidden = YES;
    [webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:nil];
    [webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';"completionHandler:nil];
}

- (UIColor *)hexColor:(NSInteger)hexValue {
    CGFloat red = (CGFloat)((hexValue & 0xFF0000) >> 16) / 255.0;
    CGFloat green = (CGFloat)((hexValue & 0xFF00) >> 8) / 255.0;
    CGFloat blue = (CGFloat)((hexValue & 0xFF)) / 255.0;
    return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}

@end
